package com.ruoyi.platform.system.verify.manager;

import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.redis.phone.PhoneCodeRedis;
import com.ruoyi.base.redis.verifycode.VerifyCodeRedis;
import com.ruoyi.base.service.BaseService;
import com.ruoyi.base.utils.thread.ThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 验证码
 *
 * @author lcf
 */
@Service
public class VerifyCodeManager extends BaseService {
    @Autowired
    private VerifyCodeRedis verifyCodeRedis;
    @Autowired
    private PhoneCodeRedis phoneCodeRedis;

    /**
     * 检查验证码
     */
    public void checkVerifyCode(String key, String code) {
        String cache = verifyCodeRedis.getCache(key);
        verifyCodeRedis.delCache(key);
        if (Objects.equals(cache, code)) {
            return;
        }

        throw exception(ExceptionEnum.CODE_ERROR);
    }

    /**
     * 检查短信验证码
     */
    public void checkPhoneVerifyCode(String phone, String code) {
        if (!Objects.equals(phoneCodeRedis.get(phone), code)) {
            throw exception(ExceptionEnum.CODE_ERROR);
        }

        //删除验证码缓存
        ThreadUtils.addTask(() -> phoneCodeRedis.del(phone));
    }
}
